//
//  SGQRCodeView.m
//  AssetsInventory
//
//  Created by 李沛池 on 2017/12/4.
//  Copyright © 2017年 李沛池. All rights reserved.
//

#import "SGQRCodeView.h"
#import <AVFoundation/AVFoundation.h>
#import "AITools.h"
#import <LPCDefine.h>

#define ScanQR_Width   (SCREEN_WIDTH*0.8)
#define ScanQR_Height  ScanQR_Width

static SGQRCodeView *_currentSGQRCodeView;

@interface SGQRCodeView ()<
AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;
@property (nonatomic, copy)   Callback currentBlock;
@property (nonatomic, strong) UIButton *flashlightBtn; //闪光灯按钮
@property (nonatomic, assign) BOOL isSelectedFlashlightBtn;

@end

@implementation SGQRCodeView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initData];
        [self initUI];
    }
    return self;
}

+ (instancetype)currentView
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _currentSGQRCodeView = [[self alloc] initWithFrame:FRAME_SCREEN];
    });
    return _currentSGQRCodeView;
}

- (void)initData
{
    self.captureSession = nil;
    self.backgroundColor = RGBACOLOR(0, 0, 0, 0.7);
}

- (void)initUI
{
    UILabel *promptLabel = [[UILabel alloc] init];
    promptLabel.backgroundColor = [UIColor clearColor];
    CGFloat promptLabelX = 0;
//    CGFloat promptLabelY = 0.73 * self.frame.size.height;
    CGFloat promptLabelY = (SCREEN_HEIGHT+ScanQR_Height)/2 - 52 + 50;
    CGFloat promptLabelW = self.frame.size.width;
    CGFloat promptLabelH = 25;
    promptLabel.frame = CGRectMake(promptLabelX, promptLabelY, promptLabelW, promptLabelH);
    promptLabel.textAlignment = NSTextAlignmentCenter;
    promptLabel.font = [UIFont boldSystemFontOfSize:13.0];
    promptLabel.textColor = [[UIColor whiteColor] colorWithAlphaComponent:0.6];
    promptLabel.text = @"将二维码/条码放入框内, 即可自动扫描";
    [self addSubview:promptLabel];
    
    _flashlightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    CGFloat flashlightBtnW = 30;
    CGFloat flashlightBtnH = 30;
    _flashlightBtn.frame = CGRectMake((SCREEN_WIDTH - flashlightBtnW)/2, promptLabelY + promptLabelH + 25, flashlightBtnW, flashlightBtnH);
    [_flashlightBtn setBackgroundImage:[UIImage imageNamed:@"SGQRCodeFlashlightOpenImage"] forState:(UIControlStateNormal)];
    [_flashlightBtn setBackgroundImage:[UIImage imageNamed:@"SGQRCodeFlashlightCloseImage"] forState:(UIControlStateSelected)];
    [_flashlightBtn addTarget:self action:@selector(flashlightAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_flashlightBtn];
    
    UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
    btnBack.frame = CGRectMake(0, 20, 54, 54);
    [btnBack setImage:ImageNamed(@"btn_back") forState:UIControlStateNormal];
    [btnBack addTarget:self action:@selector(stopReading) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:btnBack];
}

//展示扫描页面
+ (void)showScanWithCallBack:(Callback)callback
{
    SGQRCodeView *qrView = [self currentView];
    [[UIApplication sharedApplication].keyWindow addSubview:qrView];
    //判断权限
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (granted) {
                qrView.currentBlock = callback;
                [qrView startScan];
            } else {
                [AITools showAlertWithVC:qrView.viewController title:@"请在iPhone的”设置-隐私-相机“选项中，允许App访问你的相机" message:nil cancelText:@"好"];
            }
        });
    }];
}

//开始扫描
- (void)startScan
{
    NSError *error;
    //初始化捕捉设备
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@", [error localizedDescription]);
        return;
    }
    
    //创建数据输出
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    
    //创建会话
    self.captureSession = [[AVCaptureSession alloc] init];
    
    //将输入添加到会话
    [self.captureSession addInput:input];
    
    //将输出添加到会话
    [self.captureSession addOutput:captureMetadataOutput];
    
    //设置输出数据类型
    //    [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
    
    [captureMetadataOutput setMetadataObjectTypes: @[AVMetadataObjectTypeQRCode,//二维码
                                                     //以下为条形码，如果项目只需要扫描二维码，下面都不要写
                                                     AVMetadataObjectTypeEAN13Code,
                                                     AVMetadataObjectTypeEAN8Code,
                                                     AVMetadataObjectTypeUPCECode,
                                                     AVMetadataObjectTypeCode39Code,
                                                     AVMetadataObjectTypeCode39Mod43Code,
                                                     AVMetadataObjectTypeCode93Code,
                                                     AVMetadataObjectTypeCode128Code,
                                                     AVMetadataObjectTypePDF417Code]];
    
    //创建串行队列，并加媒体输出流添加到队列当中
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    
    //设置代理
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    
    //实例化预览图层
    self.videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
    
    //设置预览图层填充方式
    [self.videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    
    //设置图层的frame
    [self.videoPreviewLayer setFrame:CGRectMake((SCREEN_WIDTH-ScanQR_Width)/2, (SCREEN_HEIGHT-ScanQR_Height)/2 - 52, ScanQR_Width, ScanQR_Height)];
    
    //将图层添加到预览view的图层上
    [self.layer addSublayer:self.videoPreviewLayer];
    
    //扫描范围
    captureMetadataOutput.rectOfInterest = CGRectMake(0, 0, 1, 1);
    
    //开始扫描
    [self.captureSession startRunning];
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    //判断是否有数据
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        //判断回传的数据类型
//        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
            [self scanSuccess:[metadataObj stringValue]];
            [self performSelectorOnMainThread:@selector(stopReading) withObject:nil waitUntilDone:NO];
//        }
    }
}

//点击闪光灯按钮
- (void)flashlightAction:(UIButton *)button
{
    if (button.selected == NO) {
        [AITools openFlashlight];
        self.isSelectedFlashlightBtn = YES;
        button.selected = YES;
    } else {
        [self removeFlashlightBtn];
    }
}

//关闭手电筒
- (void)removeFlashlightBtn
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [AITools closeFlashlight];
        self.isSelectedFlashlightBtn = NO;
        self.flashlightBtn.selected = NO;
    });
}

//停止扫描
- (void)stopReading
{
    [self.captureSession stopRunning];
    self.captureSession = nil;
    [self.videoPreviewLayer removeFromSuperlayer];
    [self removeFromSuperview];
}

//扫描成功
- (void)scanSuccess:(NSString *)str
{
    SGQRCodeView *qrView = [SGQRCodeView currentView];
    if (qrView.currentBlock) {
        qrView.currentBlock(str);
    }
}



@end
